package yxy.game.pm2.bean.db.newDao;

import yxy.apple.db.DbManager;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.db.po.ItemPo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author James
 * @date 2022/1/21 16:37
 **/
public class ItemDAO {

    private static final String
            REPLACE_ONE = "replace into `item` (`pCode`, `type`, `dataId`, `number`, `updateTime`) values (?,?,?,?,?)",
            SELECT_ALL_BY_TYPE = "select * from `item` where `pCode` = ? and `type` = ?",
            DELETE = "delete from `item` where `pCode` = ? and `updateTime` != ?",
            DELETE_BY_TYPE = "delete from `item` where `pCode` = ? and `type` = ? and `updateTime` != ?";

    public static boolean replace(List<ItemPo> items) {
        List<Object[]> list = new ArrayList<>();
        for (ItemPo item : items) {
            Object[] objects = new Object[]{item.getPlayerCode(), item.getType(), item.getDataId(), item.getNumber(),item.getUpdateTime()};
            list.add(objects);
        }
        int[] ints = DbManager.instance().executeBatchCommand(REPLACE_ONE, list);
        return ints.length == items.size();
    }

    public static List<ItemPo> getList(String pCode, CurrencyType type) {
        return DbManager.instance().executeQueryObjectList(SELECT_ALL_BY_TYPE, new Object[]{pCode,type.getNumber()}, ItemPo.builder);
    }

    public static ItemPo getOneByDataId(String pCode, CurrencyType type, int dataId) {
        String sql = "select * from `item` where `pCode` = ? and `type` = ? and dataId = ?";
        List<ItemPo> itemPos = DbManager.instance().executeQueryObjectList(sql, new Object[]{pCode,type.getNumber(), dataId}, ItemPo.builder);
        return (itemPos != null && itemPos.size() > 0) ? itemPos.get(0) : null;
    }

    public static void delete(String pCode, long updateTime) {
        DbManager.instance().executeCommand(DELETE, new Object[]{pCode, updateTime});
    }

    public static void deleteByType(String pCode, CurrencyType type, long updateTime) {
        DbManager.instance().executeCommand(DELETE_BY_TYPE, new Object[]{pCode, type.getNumber(), updateTime});
    }

}
